﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Mvc;
using System.Xml.Linq;
using Mapster;
using Raffles.OA.Data;
using Raffles.OA.Utility;
using SqlSugar;

namespace Raffles.OA.WebApp.Areas.Sale.Controllers
{
    /// <summary>
    /// 日 期：2024-07-16 14:04:51
    /// 描 述：渠道管理控制器类
    /// </summary>
    public class ChannelController : BaseController<ChannelEntity>
    {
        #region 视图

        public ActionResult Form()
        {
            return View();
        }

        #endregion

        /// <summary>
        /// 获取分页列表
        /// </summary>
        /// <param name="param"></param>
        /// <param name="pagination"></param>
        /// <returns></returns>
        public async Task<ActionResult> GetPageListJson(BaseSearchParam param, Pagination pagination)
        {
            RefAsync<int> totalCount = 0;
            var datas = await _dbContext.Queryable<ChannelEntity>()
                                 .Includes(x => x.Province).Includes(x => x.City).Includes(x => x.Area)
                                 .LeftJoin<ChannelManagerEntity>((a, b) => a.Id == b.ChannelId)
                                 .WhereIF(!param.KeyWord.IsEmpty(), (a, b) => a.Name.Contains(param.KeyWord) || b.MangerName.Contains(param.KeyWord))
                                  .Select((a, b) => new ChannelVo
                                  {
                                      Id = a.Id,
                                      ChannelManagerId = b.Id,
                                      Name = a.Name,
                                      MangerName = b.MangerName,
                                      MangerPhone = b.MangerPhone,
                                      ProvinceCN = a.Province.ext_name,
                                      CityCN = a.City.ext_name,
                                      AreaCN = a.Area.ext_name,
                                      Address = a.Address
                                  })
                                  .MergeTable()
                                  .OrderBy(a => a.Id)
                                  .ToPageListAsync(pagination.PageIndex, pagination.PageSize, totalCount);
            return Content(DataResult<List<ChannelVo>>.PageResult(datas, totalCount).ToJson());
        }

        /// <summary>
        /// 获取渠道列表
        /// </summary>
        /// <returns></returns>
        public async Task<ActionResult> GetChannelSelect()
        {
            List<Dictionary<string, object>> dic =await _dbContext.Queryable<ChannelEntity>().Select(x => new { Key = x.Id, Value = x.Name }).ToDictionaryListAsync();
            return Content(DataResult<List<Dictionary<string, object>>>.Success(dic).ToJson());
        }

        /// <summary>
        /// 渠道保存
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult> SaveForm(ChannelDto channelDto)
        {
            try
            {
                await _dbContext.BeginTranAsync();

                ChannelEntity channelEntity = new ChannelEntity();
                ChannelManagerEntity channelManagerEntity = new ChannelManagerEntity();
                if (channelDto.Id == null)
                { 
                    if (_dbContext.Queryable<ChannelEntity>().Any(x => x.Name == channelDto.Name))
                    {
                        return Json(DataResult.Error("该渠道已存在！"));
                    }
                    channelDto.Adapt(channelEntity); 
                    channelEntity.CreatedBy = channelEntity.UpdatedBy = OperatorProvider.Provider.GetCurrent().Id;
                    await _dbContext.Insertable<ChannelEntity>(channelEntity).ExecuteCommandIdentityIntoEntityAsync();

                    channelManagerEntity.ChannelId = channelEntity.Id;
                    channelManagerEntity.MangerName = channelDto.MangerName;
                    channelManagerEntity.MangerPhone = channelDto.MangerPhone;
                    await _dbContext.Insertable<ChannelManagerEntity>(channelManagerEntity).ExecuteCommandAsync();
                }
                else
                {
                    if (_dbContext.Queryable<ChannelEntity>().Any(x => x.Name == channelDto.Name && x.Id != channelDto.Id))
                    {
                        return Json(DataResult.Error("该渠道已存在！"));
                    }
                    channelEntity = await _dbContext.Queryable<ChannelEntity>().InSingleAsync(channelDto.Id);
                    channelDto.Adapt(channelEntity);  
                    await _dbContext.Updateable<ChannelEntity>(channelEntity).ExecuteCommandAsync();

                    channelManagerEntity = await _dbContext.Queryable<ChannelManagerEntity>().InSingleAsync(channelDto.ManagerId);
                    if (channelManagerEntity == null)
                    {
                        channelManagerEntity = new ChannelManagerEntity();
                        channelManagerEntity.ChannelId = channelEntity.Id;
                        channelManagerEntity.MangerName = channelDto.MangerName;
                        channelManagerEntity.MangerPhone = channelDto.MangerPhone;
                        channelManagerEntity.UpdatedOn = DateTime.Now;
                        channelManagerEntity.CreatedBy = channelManagerEntity.UpdatedBy = OperatorProvider.Provider.GetCurrent().Id;
                        await _dbContext.Insertable<ChannelManagerEntity>(channelManagerEntity).ExecuteCommandAsync();
                    }
                    else
                    {
                        channelManagerEntity.MangerName = channelDto.MangerName;
                        channelManagerEntity.MangerPhone = channelDto.MangerPhone;
                        channelEntity.UpdatedOn = DateTime.Now;
                        await _dbContext.Updateable<ChannelManagerEntity>(channelManagerEntity).ExecuteCommandAsync();
                    }
                   
                    
                }

                await _dbContext.CommitTranAsync();
                return channelDto.Id == null ? Json(DataResult.Success($"新增成功")) : Json(DataResult.Success($"修改成功"));
      

            }
            catch (Exception ex)
            {
                await _dbContext.RollbackTranAsync();
                return Json(DataResult.Error($"保存失败,失败原因:{ex.Message}"));
            }
        }

        /// <summary>
        /// 编辑表单
        /// </summary>
        /// <param name="managerId"></param>
        /// <returns></returns>
        public async Task<ActionResult> SetChanelForm(int id, int? managerId)
        {
            ChannelEntity channelEntity = await _dbContext.Queryable<ChannelEntity>()
                                                          .Includes(x => x.Managers)
                                                          .InSingleAsync(id);


            ChannelManagerEntity managerEntity = channelEntity.Managers.FirstOrDefault(x => x.Id == managerId);
            ChannelVo channelVo = new ChannelVo
            {
                Id = id,
                ChannelManagerId = managerId,
                Name = channelEntity.Name,
                MangerName = managerEntity?.MangerName,
                MangerPhone = managerEntity?.MangerPhone,
                ProvinceId = channelEntity.ProvinceId,
                CityId = channelEntity.CityId,
                AreaId = channelEntity.AreaId,
                Address = channelEntity.Address
            };
            return Content(DataResult<ChannelVo>.Success(channelVo).ToJson());
        }

        /// <summary>
        /// 删除渠道经理
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult> DeleteManager(int id)
        {
            try
            {
                await _dbContext.Deleteable<ChannelManagerEntity>().In(id).ExecuteCommandAsync();
                return Json(DataResult.Success("删除成功"));
            }
            catch (Exception ex)
            {
                return Json(DataResult.Error($"删除失败,失败原因:{ex.Message}"));
            }
        }

        /// <summary>
        /// 删除渠道经理
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult> DeleteChannel(int id)
        {
            try
            {
                await _dbContext.BeginTranAsync();
                await _dbContext.Deleteable<ChannelEntity>().In(id).ExecuteCommandAsync();
                await _dbContext.Deleteable<ChannelManagerEntity>().Where(x => x.ChannelId == id).ExecuteCommandAsync();
                await _dbContext.CommitTranAsync();
                return Json(DataResult.Success("删除成功"));
            }
            catch (Exception ex)
            {
                await _dbContext.RollbackTranAsync();
                return Json(DataResult.Error($"删除失败,失败原因:{ex.Message}"));
            }
        }
    }
}
